package conqueror.com.systemupdate.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;

import conqueror.com.systemupdate.R;
import conqueror.com.systemupdate.adapter.LocalListViewAdapter;
import conqueror.com.systemupdate.bean.LocalBean;
import conqueror.com.systemupdate.util.RecoverUpdateUtil;
import conqueror.com.systemupdate.util.SDCardScanner;

public class LocalUpdateFragment extends Fragment {
    private static final String TAG = "LocalUpdateFragment";

    private TextView mTvLocal;
    private ListView mLvLocal;
    private PowerManager powerManager;
    private LocalListViewAdapter adapter;
    private String LOCALEARG;
    private String filenameArg;
    private List<LocalBean> fileDirs;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
        LOCALEARG = "--locale=zh_CN";
        filenameArg = "--update_package=";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_local, container, false);
        mTvLocal = (TextView) view.findViewById(R.id.tv_local);
        mLvLocal = (ListView) view.findViewById(R.id.lv_local);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        //如果SD卡存在,先从Sdcar查找
        if (SDCardScanner.isExternalStorage()) {
            fileDirs = SDCardScanner.getFileDir("/storage/sdcard0");
            if (fileDirs.size() == 0) {
                fileDirs = SDCardScanner.getFileDir("/storage/sdcard1");
            }
        } else {//不存在就从内置sd卡查找
            fileDirs = SDCardScanner.getFileDir("/sdcard");
        }

        if (fileDirs.size() == 0) {
            mTvLocal.setText("TF卡根目录未检测到update.zip升级包！");
            mTvLocal.setVisibility(View.VISIBLE);
            return;
        }

        adapter = new LocalListViewAdapter(getActivity(), fileDirs);
        mLvLocal.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        for (LocalBean file : fileDirs) {
            Log.e(TAG, "-----file------" + file.fileName);
            Log.e(TAG, "---------filePath------" + file.filePath);
        }


        mLvLocal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LocalBean localBean = fileDirs.get(i);
                updateDialog(localBean.fileName);
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    /**
     * dialog，确定更新或者不更新
     */
    private void updateDialog(final String fileName) {
        //挂载View并初始化
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View localView = inflater.inflate(R.layout.local_dialog, (ViewGroup) getView().findViewById(R.id.local_dialog_parent));
        Button btnEnsure = (Button) localView.findViewById(R.id.bt_localDialogOK);
        Button btnCancel = (Button) localView.findViewById(R.id.bt_localDialogCancel);
        TextView dialogMessage = (TextView) localView.findViewById(R.id.tv_dialogMessage);
        dialogMessage.setText("用该文件更新程序: \n " + fileName + "\n是否进行更新？");
        //获取biulder
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //将自己的view设置到dialog上
        final AlertDialog dialog = builder.setView(localView).create();
        dialog.setCanceledOnTouchOutside(false);//点击dialog以外而不是去焦点
//        dialog.setCancelable(false);//按back键也是没有用的
        dialog.show();

        //自定义的确定按钮
        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                //解压并重新安装系统
                try {
                    RecoverUpdateUtil.getInstance(powerManager).bootCommand("--update_package=/sdcard/" + fileName, "--locale=zh_CN");
                } catch (IOException e) {
                    Log.e("TAG", "----------SDAFDSAF------出错？？？？");
                    e.printStackTrace();
                }
            }
        });
        //自定义取消按钮
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

}
